package com.gmgx.dao;

import com.gmgx.entity.Student;
import com.gmgx.utils.JDBCUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@Repository
public class StudentDao {
    @Autowired
    private JDBCUtil jdbcUtil;

    public List<Student> queryAllStudent(){
        String sql = "select sno,sname,password,photo,resume from t_student";
        ResultSet rs = jdbcUtil.doQuery(sql);
        List<Student> stuList = new ArrayList<>();
        try {
            while (rs.next()){
                Student stu = new Student();
                stu.setSno(rs.getInt("sno"));
                stu.setSname(rs.getString("sname"));
                stu.setPassword(rs.getString("password"));
                stu.setPhoto(rs.getString("photo"));
                stu.setResume(rs.getString("resume"));
                stuList.add(stu);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            jdbcUtil.doClose(rs);
        }
        return stuList;
    }
    public boolean register(Student student){
        String sql = "insert into t_student(sname,password) values(?,?)";
        int key = jdbcUtil.doAddObject(sql, student.getSname(), student.getPassword());
        student.setSno(key);
        return key>0;
    }

    public boolean modifyStudentPhoto(Integer sno, String photo) {
        String sql = "update t_student set photo=? where sno=?";
        int count = jdbcUtil.doUpdate(sql, photo, sno);

        return count > 0;
    }

    public boolean modifyStudentResume(Integer sno, String resume) {
        String sql = "update t_student set resume=? where sno=?";
        int count = jdbcUtil.doUpdate(sql, resume, sno);

        return count > 0;
    }

    public Student queryStudentBySno(Integer sno) {
        String sql = "select sno,sname,password,photo,resume from t_student where sno=?";
        ResultSet rs = jdbcUtil.doQuery(sql, sno);
        Student stu = null;
        try{
            while (rs.next()){
                stu = new Student();
                stu.setSno(rs.getInt("sno"));
                stu.setSname(rs.getString("sname"));
                stu.setPassword(rs.getString("password"));
                stu.setPhoto(rs.getString("photo"));
                stu.setResume(rs.getString("resume"));
            }
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            jdbcUtil.doClose(rs);
        }
        return stu;

    }
}
